import { loginApi, logout, getInfo } from "@/api/user";
import {
  getToken,
  setToken,
  removeToken,
  setuserId,
  getuserId,
  removeuserId,
} from "@/utils/auth";
import { resetRouter } from "@/router";

const getDefaultState = () => {
  return {
    token: getToken(),
    userid: getuserId(),
    userInfo: {},
  };
};

const state = getDefaultState();

const mutations = {
  updateToken(state, token) {
    state.token = token;
    setToken(token);
  },
  updateUserid(state, id) {
    state.userid = id;
    setuserId(id);
  },
  delToken(state) {
    removeToken();
    state.token = null;
    removeuserId();
    state.userid = null;
  },
  deluserInfo(state, data) {
    state.userInfo = data;
  },
};

const actions = {
  async login(context, data) {
    const res = await loginApi(data);
    console.log(res);
    context.commit("updateToken", res.token.token);
    context.commit("updateUserid", res.user.id);
  },
  async getUserInfo({ state }) {
    const res = await getUserInfoApi(state.userid);
    state.userInfo = res;
  },
  logout({ commit }) {
    commit("delToken");
    commit("deluserInfo", {});
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
